package com.dongdong.service.impl;

import com.dongdong.mapper.TbItemMapper;
import com.dongdong.model.TbItem;
import com.dongdong.model.TbItemExample;
import com.dongdong.service.ItemService;
import com.dongdong.vo.ItemVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    private TbItemMapper itemMapper;


    @Override
    public List<ItemVO> getItemById(Long id) {
        TbItemExample example = new TbItemExample();
        example.createCriteria().andGoodsIdEqualTo(id);
        List<TbItem> tbItems = itemMapper.selectByExample(example);

        return tbItems.stream().map(item -> {
            ItemVO itemVO = new ItemVO();
            BeanUtils.copyProperties(item, itemVO);
            return itemVO;
        }).collect(Collectors.toList());
    }

    @Override
    public ItemVO getIemBySKUId(Long skuid) {
        TbItem tbItem = itemMapper.selectByPrimaryKey(skuid);
        ItemVO vo = new ItemVO();
        BeanUtils.copyProperties(tbItem, vo);
        return vo;
    }

    @Override
    public void subStockCount(List<TbItem> kc) {
        for (TbItem tbItem : kc) {
            //根据id查询数据库
            TbItem tbItem1 = itemMapper.selectByPrimaryKey(tbItem.getId());
            //减库存
            tbItem1.setStockCount(tbItem1.getStockCount() - tbItem.getNum());
            //修改数据库
            itemMapper.updateByPrimaryKeySelective(tbItem1);
        }
    }
}
